<template>
    <textarea ref="query"></textarea>
</template>
<script setup>
import { CodeMirror } from '../../libs/CodeMirror'
import { nextTick, ref, watch } from 'vue'
import format from '../../libs/format'
const query = ref(null);
const props = defineProps(['ContentData', 'activeKey']);

const beautify = (source) => {
    function looks_like_html(source) {
        var trimmed = source.replace(/^[ \t\n\r]+/, '');
        return trimmed && (trimmed.substring(0, 1) === '<');
    };
    var output,
        opts = {
            // brace_style : "expand"
        };
    opts.indent_char = ' ';
    opts.preserve_newlines = "-1";
    if (looks_like_html(source)) {
        output = html_beautify(source, opts);
    } else {
        output = js_beautify(source, opts);
    };
    return output;
};
var Textarea = null;
nextTick(() => {
    Textarea = CodeMirror.fromTextArea(query.value, {
        mode: 'text/javascript',
        indentWithTabs: true,
        smartIndent: false,
        lineNumbers: true,
        lineWrapping: true,
        foldGutter: true,
        matchBrackets: true,
        gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
        theme: 'mdn-like',
    });
    Textarea.on('beforeChange', (instance, changeObj) => {
        if (changeObj.origin == '+input' && (changeObj.text == '\'' || changeObj.text == '\"')) {
            var _str = Textarea.getSelection();
            if (_str.toString().length > 0) {
                Textarea.replaceSelection(_str + _str + changeObj.text);
            };
        };
    });
    for (const key in props.ContentData.item.body) {
        const element = props.ContentData.item.body[key];
        var _String = format.String(element, props.ContentData.folder.models);
        var str = beautify(_String);
        Textarea.setValue(str);
    }
})

watch(() => props.activeKey, (val) => {
    if (val == 'body') {
        setTimeout(() => {
            Textarea.refresh();
        }, 10)
    }
})

const getValue = () => Textarea.getValue();


defineExpose({
    getValue
})


</script>
<style lang="less" scoped>

</style>